package com.qiangesoft.rdp.starter.mvc.validate;

import lombok.SneakyThrows;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

/**
 * 枚举值校验器
 *
 * @author qiangesoft
 * @date 2023-09-18
 */
public class EnumValueValidator implements ConstraintValidator<EnumValue, String> {

    private IEnum[] enums;

    @SneakyThrows
    @Override
    public void initialize(EnumValue constraintAnnotation) {
        enums = constraintAnnotation.clazz().getEnumConstants();
    }

    @Override
    public boolean isValid(String code, ConstraintValidatorContext context) {
        if (Objects.isNull(code)) {
            return false;
        }
        for (IEnum iEnum : enums) {
            if (iEnum.getCode().equals(code)) {
                return true;
            }
        }
        return false;
    }
}
